How to Remove Special Character from String in PHP ?

admin_img Posted By Bajarangi soft , Posted On 31-12-2020

We have given a string and the task is to remove special characters from a string str in PHP. In order to do this task, we have the following methods in PHP:

Remove a special character in PHP

Method 1: Using str_replace() MethodThe str_replace() method is used to remove all the special character from the given string str by replacing these character with the white space (” “).

Syntax:

str_replace( $searchVal, $replaceVal, $subjectVal, $count )

Example:

<?php 
// PHP program to Remove 
// Special Character From String 
    
// Function to remove the spacial 
function RemoveSpecialChar($str) { 
    
    // Using str_replace() function 
    // to replace the word 
    $res = str_replace( array( '\'', '"', 
    ',' , ';', '<', '>' ), ' ', $str); 
    
    // Returning the result 
    return $res; 
    } 

// Given string 
$str = "Example,to remove<the>Special'Char;"; 

// Function calling 
$str1 = RemoveSpecialChar($str); 

// Printing the result 
echo $str1; 
?>

Method 2: Using str_ireplace() MethodThe str_ireplace() method is used to remove all the special character from the given string str by replacing these character with the white space (” “). The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive.
Syntax:

str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )

Example:

preg_replace( $pattern, $replacement, $subject, $limit, $count )
<?php 
// PHP program to Remove 
// Special Character From String 
    
// Function to remove the spacial 
function RemoveSpecialChar($str){ 
    
    // Using str_ireplace() function 
    // to replace the word 
    $res = str_ireplace( array( '\'', '"', 
    ',' , ';', '<', '>' ), ' ', $str); 
    
    // returning the result 
    return $res; 
    } 

// Given string 
$str = "Example,to remove<the>Special'Char;"; 

// Function calling 
$str1 = RemoveSpecialChar($str); 

// Printing the result 
echo $str1; 
?>

Syntax:

str_replace( $searchVal, $replaceVal, $subjectVal, $count )

Method 3: Using preg_replace() MethodThe preg_replace() method is used to perform a regular expression for search and replace the content.

Syntax:

preg_replace( $pattern, $replacement, $subject, $limit, $count )

Example:

<?php 
// PHP program to Remove 
// Special Character From String 
    
// Function to remove the spacial 
function RemoveSpecialChar($str){ 
    
    // Using preg_replace() function 
    // to replace the word 
    $res = preg_replace('/[^a-zA-Z0-9_ -]/s',' ',$str); 
    
    // Returning the result 
    return $res; 


// Given string 
$str = "Example,to remove<the>Special'Char;"; 

// Function calling 
$str1 = RemoveSpecialChar($str); 

// Printing the result 
echo $str1; 
?>
 

 

Related Post